package com.tqyan.start.controller;

import com.tqyan.model.Result;
import com.tqyan.model.exp.DefaultException;
import com.tqyan.service.service.SoundService;
import com.tqyan.service.transfer.FileService;
import com.tqyan.service.transfer.LimitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @description 语音API
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @date 2023/4/15 19:35
 */
@RestController
@RequestMapping("/sound/")
@Slf4j
//@Api(tags = "语音API")
public class SoundController {

    @Autowired
    private FileService fileService;
    @Autowired
    private SoundService soundService;
    @Autowired
    private LimitService limitService;

    @PostMapping("/dictation")
//    @ApiOperation(value = "语音识别")
    public Result<String> dictation(@RequestParam("openId") String openId, @RequestParam("file") MultipartFile file) {
        if (StringUtils.isBlank(openId)
                || null == file) {
            return Result.fail("请求参数不可为空");
        }
        log.info("[语音识别] openId={}, 语音识别", openId);
        boolean isLock = limitService.lock(openId);
        if (!isLock) {
            return Result.fail("让小燕子休息一会吧");
        }
        try {
            return Result.success(soundService.soundDictation(openId, fileService.convertUploadFile(file)));
        } catch (DefaultException e) {
            log.error("[语音识别] openId={}, 语音识别, 异常: {}", openId, e.getMessage(), e);
            return Result.fail(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error("[语音识别] openId={}, 语音识别, 异常: {}", openId, e.getMessage(), e);
            return Result.fail(e.getMessage());
        } finally {
            limitService.unlock(openId);
        }
    }

}


